package com.train.mybatis.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.train.common.utils.helper.UserHelper;
import com.train.common.utils.id.SnowIdUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        //自动创建id
        this.strictInsertFill(metaObject, "id", Long.class, SnowIdUtils.getNextId());
        // 自动填充创建时间
        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
        // 自动填充更新时间
        this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
        // 自动填充创建人（假设从上下文中获取）
        if (metaObject.hasSetter("createUser")) {
            this.strictInsertFill(metaObject, "createUser", String.class, getUserId());
        }
        if (metaObject.hasSetter("updateUser")) {
            // 自动填充更新人（假设从上下文中获取）
            this.strictInsertFill(metaObject, "updateUser", String.class, getUserId());
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        // 自动填充更新时间
        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
        // 自动填充更新人（假设从上下文中获取）
        if (metaObject.hasSetter("updateUser")) {
            this.strictUpdateFill(metaObject, "updateUser", String.class, getUserId());
        }
    }

    private String getUserId() {
        Long userId = UserHelper.getUserId();
        return userId == null ? "def_user" : String.valueOf(userId);
    }
}